<?php

class Csv_handler extends CI_Controller {

	function __construct()
	{
		parent::__construct();

		$this->load->library('csv_reader');
		setlocale(LC_ALL, 'ja_JP.UTF-8');

	}

	function index()
	{
		//$this->load->view('test/test', array('error' => ' ' ));
		$this->load->view('admin/csv_vv', array('error' => ' ' ));
		//$this->load->view('admin/csv_v', array('error' => ' ' ));
	}

	function do_export()
	{
		$data = $this->common_model-> export_csv($_POST['tbl_nm']);
		$rtnMsg = '';

		if (is_array($data)) {
			foreach ($data as $key => $value) {

				if ( ! write_file('./exports/'.$key.'.csv', $value)) {
					$rtnMsg = $rtnMsg.$key.'はファイルに書き込めません';

				}
			}

		} else {
			if ($data == "") {
				$rtnMsg = $_POST['tbl_nm'].'テーブルデータは存在しません';
			} else {

				if ( ! write_file('./exports/'.$_POST['tbl_nm'].'.csv', $data))
				{
					$rtnMsg = 'ファイルに書き込めません';
				}
				else
				{
					$rtnMsg = 'ファイルが書き込まれました!';
				}
			}
		}
		$this->load->view('admin/csv_v', array('error' => $rtnMsg ));
	}




	function importcsv() {

		$rtnMsg = '';
		$eraArray = array();

		$fname = $_FILES['userfile']['name'];

		if(!empty($fname))
		{
		     $fname = $_FILES['userfile']['name'];

		     $chk_ext = explode(".",$fname);//table_name.csv

		     if(strtolower($chk_ext[1]) == "csv")
		     {

		         $filename = $_FILES['userfile']['tmp_name'];
		         $handle = fopen($filename, "r");

		    	// table名（$chk_ext[0])にてライブラリから情報を取得
		    	$entity_info = $this->csv_reader->get_entity_info($chk_ext[0]);

			    	//echo "<br />-----entity_info------<br />";
			    	//print_r( $entity_info );

		    	$cnt = 0;


		    	//csvファイルのデータ
		         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
		         {
			         	//echo "<br />------csv_data-----";
	         			//print_r( $data );
	         			//echo "<br />";

         			/*check処理START*/
         			$boo_check = true;
         			$check_info = $entity_info[1];
         			foreach ($check_info as $key => $values) {
         					//echo "<br />-----check_tableNm : ".$key;
         				$check_tabl = $key;
	         				//echo "<br />----check_values----<br />";
	         				//print_r($values);

		            	//個別項目のvalidation checkはしない・・・DB insert エラーでOK
		            	//tableにキーが存在するかチェック
         				$whereArray = array();
						$boo_tf = $values[0];
         				for ($k=1 ; $k < count($values) ; $k++) {
         					//if ($cnt_X === 0) continue; //header区分、あと追加
         					//echo "<br />----value".$k."---------";
         					//echo $values[$k];
         					$whereArray[$values[$k]] =  $data[$k-1];
         				}
	         				//echo "<br />---whereArray----".$boo_tf."<br />";
	         				//print_r($whereArray);
		            	if ($this->common_model->unique_check(
		            			$check_tabl, $whereArray) == $boo_tf) {
		            		//echo "era";
		            		$eraArray[] = ($cnt."行目era-");
		            		//ato 解放 $boo_check = false;
		            		$boo_check = false;
		            		break;
		            	}
         			}//foreach : check処理
         			if (!$boo_check) {
         				$cnt++;
         				continue;
         			}
         			/*check処理END*/

         				//echo "<br />---DATA-IMPORT処理START----<br />";
         			/*DATA-IMPORT処理START*/
         			//データCONVERT

	         			// echo "<br />---entity_info[0]----<br />";
	         			// print_r( $entity_info[0] );
	         			// echo "<br />";
	         			// print_r( $data );

         			 $data_values = $entity_info[0];
         			 $data_cnt = 0;
         			foreach ($data_values as $key => $value) {
         					//echo "<br />". $key."<br />";//TEST
         				$data_values[$key] = $data[$data_cnt];
         				//$entity_info[0][$key] = $data[$data_cnt];
         				$data_cnt++;
         			}
	         			//echo "<br />".$cnt++."---after --entity_info----<br />";
	         			// print_r( $data_values );

					//DEFAULT値指定
         			$data_values['created_user'] = 'pkyppp';
         			$data_values['created_datetime'] = 'now()';
         			$data_values['updated_user'] = 'pkyppp';
         			$data_values['updated_datetime'] = 'now()';//<--出来ない
	         			//echo "<br />".$cnt++."---rrr --data_values----<br />";
	         			//print_r( $data_values );

	            	$this->common_model-> common_insert($chk_ext[0], $data_values);

	            	$cnt++;
		         }//while
		         /*DATA-IMPORT処理END*/

			         //echo "<br />-----eraArray---";
			        // print_r( $eraArray );
			           // $sql = "INSERT into user(name,email,phone) values('$data[0]','$data[1]','$data[2]')";
			           // mysql_query($sql) or die(mysql_error());

		         fclose($handle);
		         foreach ($eraArray as $k => $v){
		         	echo  $k.$v;
		         }
		         if (!empty($eraArray)) {
		         	 $rtnMsg =  "Failed Imported";
		         } else {
		         	 $rtnMsg =  "Successfully Imported";
		         }
		     }
		     else  {
		         $rtnMsg = "Invalid File";
		     }
		}
		else {
         	$rtnMsg = "empty File";
     	}

		//$this->load->view('admin/csv_v', array('error' => $rtnMsg, 'errorArray' => $eraArray ));
		$this->load->view('admin/csv_vv', array('error' => ' ' ));
	}


}
?>